package com.winit.uCloud.util;

import com.winit.common.util.ConfigUtil;
import com.winit.common.util.JSONFileUtil;
import com.winit.common.util.ShellRunUtil;
import com.winit.uCloud.bean.UCloudCInfo;
import com.winit.uCloud.bean.UCloudCTargetInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;

/**
 * Created by wangjian on 16/10/28.
 */
public class UCloudUtil {

    private static Logger logger = LoggerFactory.getLogger(UCloudUtil.class);

    //    public static final String UCLOUD_DIR = ConfigUtil.getValue("rootPath")+"Beetle/uCloud/";
    public static final String UCLOUD_DIR = ConfigUtil.getValue("ucloud_root_path");

    public static UCloudCInfo getCTargetInfo(String ucloudIp) {
        List<UCloudCInfo> list = JSONFileUtil.getFileJsonForList(ConfigUtil.getValue("ucloud_c_redis_list_file"), UCloudCInfo.class);
        if (list.size() == 0)
            return null;

        UCloudCInfo info = null;
        for (UCloudCInfo i : list) {
            if (ucloudIp.equals(i.getcIp())) {
                info = i;
                break;
            }
        }
        return info;
    }

    //启动OGG
    public static Map<String, Object> startOGG(UCloudCTargetInfo info) {
        return runOggCmd(info, "start");
    }

    //获取ogg目标端同步量
    public static Map<String, Object> getOggTargetTotal(UCloudCTargetInfo info) {
        return runOggCmd(info, "ggs_check_total");
    }

    //停止
    public static Map<String, Object> stopOGG(UCloudCTargetInfo info) {
        return runOggCmd(info, "stop");
    }

    //获取ogg服务状态
    public static Map<String, Object> OGGStatus(UCloudCTargetInfo info) {
        return runOggCmd(info, "status");
    }

    //判断ogg数据是否同步完成
    public static boolean isOggComplete(UCloudCTargetInfo info) {
        Map<String, Object> map = runOggCmd(info, "ggs_lag");
        if ((Integer) map.get("code") != 0) {
            return false;
        }
        if ("ok".equalsIgnoreCase((String) map.get("message"))) {
            return true;
        }
        return false;
    }

    public static Map<String, Object> runOggCmd(UCloudCTargetInfo info, String oggCmd) {
        StringBuffer cmd = new StringBuffer();
        cmd.append("sshpass -p ").append(info.getPassword()).append(" ssh -p ").append(info.getSshPort()).append(" ")
                .append(info.getUser()).append("@").append(info.getIp())
                .append(" 'source /etc/profile && cd /home/ogg && bash ggs_extract.sh ").append(oggCmd).append(" '");
        Map<String, Object> map = ShellRunUtil.runCmdsMap(cmd.toString());
        logger.info("com.winit.uCloud.util.UCloudUtil.runOggCmd ip:" + info.getIp() + ";cmd:" + oggCmd + " ;map:" + map);
        return map;
    }

}
